package cn.akwangl.socket.aio.simple;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * AIO client 实现.
 *
 * @author 阿坤同学
 * @date 2022/6/26 17:20
 * @since 0.0.6
 */
@Slf4j
public class Client {

    private AsynchronousSocketChannel socketChannel;
    private Charset charset = StandardCharsets.UTF_8;

    private void start() {
        try {
            socketChannel = AsynchronousSocketChannel.open();
            Future<Void> connect = socketChannel.connect(new InetSocketAddress(AIOSimpleService.SERVER_ADDRESS, AIOSimpleService.SERVER_PORT));
            connect.get();
            log.info("服务器连接成功...");
            Scanner scanner = new Scanner(System.in);
            while (true) {
                //  写
                String msg = scanner.nextLine();
                ByteBuffer writeBuffer = ByteBuffer.wrap(msg.getBytes());
                Future<Integer> echo = socketChannel.write(writeBuffer);
                echo.get();

                //  读
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                readBuffer.clear();
                Future<Integer> read = socketChannel.read(readBuffer);
                read.get();
                readBuffer.flip();
                log.info("服务端消息:{}", charset.decode(readBuffer));
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                log.error("客户端关闭异常", e);
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}